/*******************************************************************************
 * Copyright (c) 2012, 2013 XML-Print Project.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     XML-Print Project - initial API and implementation
 ******************************************************************************/
package info.xmlprint.util;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Scrollable;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Tree;

public class ResizeColumns implements ControlListener {

	private Composite comp;
	private Scrollable control;

	@Override
	public void controlMoved(ControlEvent arg0) {

	}

	public ResizeColumns(Composite comp, Scrollable control) {
		this.comp = comp;
		this.control = control;
	}

	@Override
	public void controlResized(ControlEvent arg0) {
		comp.addControlListener(new ControlAdapter() {
			public void controlResized(ControlEvent e) {
				Rectangle area = comp.getClientArea();
				int headHeight = 0;

				if (control instanceof Tree) {
					headHeight = ((Tree) control).getHeaderHeight();

				} else if (control instanceof Table) {
					headHeight = ((Table) control).getHeaderHeight();
				}

				int width = area.width - 2 * control.getBorderWidth();
				if (control.computeSize(SWT.DEFAULT, SWT.DEFAULT).y > area.height
						+ headHeight) {
					width -= ((Scrollable) control).getVerticalBar().getSize().x;
				}

				int oldSize = control.getSize().x;
				if (oldSize > area.width) {
					setColumn(control, width);
					control.setSize(area.width, area.height);
				} else {
					control.setSize(area.width, area.height);
					setColumn(control, width);
				}

			}
		});

	}

	private void setColumn(Control control, int width) { 
		int w = 0;
		int wSumme = 0;
		int count;
		if (control instanceof Tree) {
			Tree tree = (Tree) control;
			count = tree.getColumnCount();
			w = width / count;
			for (int i = 0; i < count; i++) {
				if (i == count - 1) {
					w = width - wSumme;
				} else {
					wSumme += w;
				}
				tree.getColumn(i).setWidth(w);
			}

		} else if (control instanceof Table) {
			Table table = (Table) control;
			count = table.getColumnCount();
			w = width / count;
			for (int i = 0; i < count; i++) {
				if (i == count - 1) {
					w = width - wSumme;
				} else {
					wSumme += w;
				}
				table.getColumn(i).setWidth(w);
			}
		}

	}

}
